package com.auto.survey.activity.bluetooth

import android.bluetooth.BluetoothDevice
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.recyclerview.widget.RecyclerView
import com.auto.survey.R

class BluetoothDeviceAdapter(
    private var deviceItems: MutableList<BluetoothDevice>,
    private val itemClickListener: (BluetoothDevice, Int) -> Unit
) : RecyclerView.Adapter<BluetoothDeviceAdapter.DeviceViewHolder>() {

    private var connectingPosition = RecyclerView.NO_POSITION

    fun updateDevices(newDevices: List<BluetoothDevice>) {
        this.deviceItems.clear()
        this.deviceItems.addAll(newDevices)
        connectingPosition = RecyclerView.NO_POSITION
        notifyDataSetChanged()
    }



    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): DeviceViewHolder {
        val view = LayoutInflater.from(parent.context)
            .inflate(R.layout.item_bluetooth_device, parent, false)
        return DeviceViewHolder(view)
    }

    override fun onBindViewHolder(holder: DeviceViewHolder, position: Int) {
        val deviceItem = deviceItems[position]
        holder.bind(deviceItem)


        // 点击事件处理
        holder.root.setOnClickListener {
            // 通知Activity/Fragment处理连接逻辑
            itemClickListener(deviceItem, position)
        }
    }

    override fun getItemCount(): Int = deviceItems.size

    inner class DeviceViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {

        private val devName: TextView = itemView.findViewById(R.id.tvDeviceName)
        private val macAddr: TextView = itemView.findViewById(R.id.tvDeviceAddress)
        val root = itemView.findViewById<ConstraintLayout>(R.id.cl_blueitem)

        fun bind(device: BluetoothDevice) {
            devName.text = device.name ?: "未知设备"
            macAddr.text = device.address
        }
    }
}
